package uy.edu.fing.pgsegesb.utils;

import java.io.StringReader;
import java.io.StringWriter;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.DOMOutputter;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class XmlHelper {

	public static String xmlAsPlainString(Element body) throws Exception
	{
		return plainString(XmlHelper.elementToString(body));
	}
	
	public static String plainString(String str)
	{
		return str.replaceAll("\r", "").replaceAll("\n", "");
	}
	
	public static Document fileToXML(String xmlFilePath) throws Exception {
		 
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
		Document doc = docBuilder.parse (xmlFilePath);
         
		return doc;
	}
	
	public static Document stringToXML(String xmlString) throws Exception {
		SAXBuilder saxBuilder = new SAXBuilder();
	    org.jdom2.Document doc = saxBuilder.build(new StringReader(xmlString));
	    //String message = doc.getRootElement().getText();
	    DOMOutputter out = new DOMOutputter();
        org.w3c.dom.Document domDoc= out.output(doc);
        System.out.println(domDoc.getImplementation().toString());
	    return domDoc;
	}
	
	public static String xmlToString(Document xml) throws Exception {
		
		StringWriter stringWriter = new StringWriter(); 
        Transformer transformer = TransformerFactory.newInstance().newTransformer(); 
        transformer.transform(new DOMSource(xml), new StreamResult(stringWriter)); 
        return stringWriter.toString(); 
        }
	
	public static String elementToString(Element node) throws Exception
	{
		TransformerFactory transFactory = TransformerFactory.newInstance();
		Transformer transformer = transFactory.newTransformer();
		StringWriter buffer = new StringWriter();
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		transformer.transform(new DOMSource(node),
		      new StreamResult(buffer));
		String str = buffer.toString();
		return str;
	}
}
